/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controle;

import dao.Dao;
import entidades.Editora;
import entidades.Upload;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Maria Eloyza
 */
public class EditoraServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet EditoraServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet EditoraServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {
            out.close();
        }
    }

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Dao<Editora> daoE = new Dao<Editora>(Editora.class);
        HttpSession session = request.getSession(true);
        String op = request.getParameter("op");

        if (op.equals("Remover")) {
            Editora e = daoE.get(id);
            
            Upload.removeFile(getServletContext().getRealPath(dir), e.getFoto());
            
            daoE.remove(id);

            List<Editora> editoras = daoE.list();
            request.setAttribute("editoras", editoras);

            RequestDispatcher rd = request.getRequestDispatcher("editora.jsp");
            rd.forward(request, response);
        }
        if (op.equals("Editar")) {
            Editora e = daoE.get(id);
            session.setAttribute("objetoEditora", e);

            response.sendRedirect("editarEditora.jsp");
        }
    }
    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    public final String dir = "/files/";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //Cria um objeto upload já setando e criando o diretorio que os
        // arquivos serão armazenados
        Upload upload = new Upload(getServletContext().getRealPath(dir));
        HttpSession session = request.getSession(true);

        // Retorna um list com todos os componentes de uma requisição
        List list = upload.processRequest(request);

        // Neste Map você obteve todos os campos do formulário.
        Map<String, String> map = upload.getFormValues(list);

        String nome = map.get("nome");
        String telefone = map.get("telefone");
        String endereco = map.get("endereco");
        String email = map.get("email");
        String op = map.get("op");
        String imagem = map.get("imagem0");
        Dao<Editora> daoE = new Dao<Editora>(Editora.class);

        if (op.equals("Buscar")) {
            List<Editora> editoras;
            if (nome == null) {
                nome = "";
            }
            editoras = daoE.listByNome(nome);

            request.setAttribute("buscou", true);

            request.setAttribute("editoras", editoras);
        }
        if (op.equals("Inserir")) {
            Editora e = new Editora();
            e.setNome(nome);
            e.setTelefone(telefone);
            e.setEndereco(endereco);
            e.setEmail(email);
            e.setFoto(imagem);
            daoE.insert(e);

            List<Editora> editoras = daoE.list();
            session.setAttribute("objetoEditora", e);
            request.setAttribute("editoras", editoras);
        }
        if (op.equals("Editar")) {
            Editora e = (Editora) session.getAttribute("objetoEditora");
            e.setNome(nome);
            e.setTelefone(telefone);
            e.setEndereco(endereco);
            e.setEmail(email);

            if (imagem != null) {
                e.setFoto(imagem);
            }

            daoE.update(e);

            List<Editora> editoras = daoE.list();

            session.removeAttribute("objetoEditora");
            request.setAttribute("editoras", editoras);
        }
        RequestDispatcher rd = request.getRequestDispatcher("editora.jsp");
        rd.forward(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
